const audioUtils  = require('../utils/audioUtils');
const g = require('../utils/global');

cc.Class({
    extends: cc.Component,

    properties: {
        bombWhite: {
            type: cc.Prefab,
            default: null,
        },
        crushEffect: {
            type: cc.Prefab,
            default: null,
        },
        audioUtils: {
            type: audioUtils,
            default: null,
        }
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {

    },

    // 爆炸特效
    playEffects(effectQueue) {
        if(!effectQueue || effectQueue.length < 1) {
            return;
        }

        let soundMap = {};
        effectQueue.forEach(cmd => {
           const  delayTime = cc.delayTime(cmd.playTime);
           const callFunc = cc.callFunc(function () {
               cc.log(`play effect action = ${cmd.action}`);
               let instantEffect = null;
               let animation = null;
               if(cmd.action === g.CELL_EFFECT_ACTION.crush) {
                   instantEffect = cc.instantiate(this.crushEffect);
                   animation = instantEffect.getComponent(cc.Animation);
                   animation.play(g.CELL_ANIM.effect);
                   !soundMap['crush'+cmd.playTime] && this.audioUtils.playEliminate(cmd.step);
                   soundMap['crush'+cmd.playTime] = true;
               } else if (cmd.action === g.CELL_EFFECT_ACTION.rowBomb) {
                   instantEffect = cc.instantiate(this.bombWhite);
                   animation = instantEffect.getComponent(cc.Animation);
                   animation.play(g.CELL_ANIM.effectLine);
               } else if (cmd.action === g.CELL_EFFECT_ACTION.colBomb) {
                   instantEffect = cc.instantiate(this.bombWhite);
                   animation = instantEffect.getComponent(cc.Animation);
                   animation.play(g.CELL_ANIM.effectCol);
               }
               // play animation
               if(instantEffect && animation) {
                   const x = (g.CELL_WIDTH+ g.OFFSET_X)*(cmd.pos.y - 0.5);
                   const y = g.GRID_HEIGHT - (g.OFFSET_Y+ g.CELL_HEIGHT)*(cmd.pos.x-0.5);
                   instantEffect.x = x;
                   instantEffect.y = y;
                   instantEffect.parent = this.node;
                   animation.on('finished', function () {
                       instantEffect.destroy();
                   }, this)
               }
           }, this);
           this.node.runAction(cc.sequence(delayTime, callFunc));
           // 添加对象属性,否则无法取到 this.node
        }, this);

    }
    // update (dt) {},
});
